package com.ruoyi.common.core.result;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author by shixd
 * @date 2021/3/23
 * @desc
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {


    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Result) { //发生异常之后，异常处理器里面返回的已经是Result了
            return body;
        } else if (body instanceof String) { //String属于特殊情况，需要单独处理，否则会报错
            try {
                return objectMapper.writeValueAsString(ResultUtils.success(body));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                return ResultUtils.error(ResultEnum.UNKNOWN_ERROR.getCode(), e.getMessage());
            }
        }
        return ResultUtils.success(body);
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return false;
    }
}
